package com.vitalc.service.common;

import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenzihao
 * @date 2020/12/14
 */
@Getter
public enum MyEnum {

    TEST_ENUM1(1, "测试枚举1"),
    TEST_ENUM2(2, "测试枚举2"),
    TEST_ENUM3(3, "测试枚举3"),

    UN_KNOW(-1, "未知"),
    ;

    private Integer code;

    private String name;

    MyEnum(Integer code, String name) {
        this.code = code;
        this.name = name;
    }

    // 空间换时间
    private static Map<Integer, MyEnum> codeMapping = new HashMap<>();

    private static Map<String, MyEnum> nameMapping = new HashMap<>();

    static {
        for (MyEnum myEnum : MyEnum.values()) {
            codeMapping.put(myEnum.code, myEnum);
            nameMapping.put(myEnum.name, myEnum);
        }
    }

    public static MyEnum valueOf(int code) {
        if (!codeMapping.containsKey(code)) {
            return UN_KNOW;
        }
        return codeMapping.get(code);
    }

    public static MyEnum nameOf(String name) {
        if (!nameMapping.containsKey(name)) {
            return UN_KNOW;
        }
        return nameMapping.get(name);
    }

    // 循环写法
    public static MyEnum getEnumByName(String name) {
        if ("".equals(name)) {
            return null;
        }
        for (MyEnum myEnum: MyEnum.values()) {
            if (myEnum.getName().equals(name)) {
                return myEnum;
            }
        }
        return null;
    }

}
